<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%; margin-top: 20px">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employee'
import { getImportJsData } from '@/utils/excel'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // 1.拿到数据 通过格式化方法 处理成后端要求的数据格式
      // 2.调用真实接口传递数据
      const headerRelation = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName'
      }
      const formatData = getImportJsData(results, headerRelation)
      await importEmployee(formatData)
      this.$message.success('导入成功')
      // 导入成功后跳回到上一页
      this.$router.back()
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>
